const Mock = require('mockjs')
const { param2Obj } = require('./utils')

const user = require('./user')
const table = require('./table')
// const testTest=require("./test-test")
const course=require('./course')
const classroom=require('./classroom/classroom')
const subscriber=require('./subscriber/subscriber')
const devices=require('./devices/devices')
const mocks = [
  ...user,//对象数组
  ...table,
  ...devices
]

// for front mock
// please use it cautiously, it will redefine XMLHttpRequest,
// which will cause many of your third-party libraries to be invalidated(like progress event).
function mockXHR() {
  // mock patch
  // https://github.com/nuysoft/Mock/issues/300
  Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  Mock.XHR.prototype.send = function() {
    if (this.custom.xhr) {
      this.custom.xhr.withCredentials = this.withCredentials || false

      if (this.responseType) {
        this.custom.xhr.responseType = this.responseType
      }
    }
    this.proxy_send(...arguments)
  }

  function XHR2ExpressReqWrap(respond) {
    return function(options) {
      let result = null
      if (respond instanceof Function) {
        const { body, type, url } = options
        // https://expressjs.com/en/4x/api.html#req
        result = respond({
          method: type,
          body: JSON.parse(body),
          query: param2Obj(url)
        })
      } else {
        result = respond
      }
      return Mock.mock(result)
    }
  }

  for (const i of mocks) {
    Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
  }
}

// const fs=require('fs');
// const path=require('path');
// // const Mock = require('mockjs')最上面已经有了
// const JSON5=require('json5');
// function getJsonFile(filePath){
//   //读取指定的json文件
//   var json = fs.readFileSync((path.resolve(__dirname,filePath), 'utf-8'));
//   //解析并返回
//   return JSON5.parse(json);
// }
// function f(app){
//   //监听http请求
//   app.get('/user/userinfo2',function(rep,res) {
//     //每次响应请求时读取mock data的json文件
//     //上面的getJsonFile方法定义了如何读取json文件并解析数据对象
//     var json=getJsonFile('./userInfo.json5');
//     //将json传入 Mock.mock 方法中，生成随机数据返回给浏览器。
//     console.log("进入了这个函数")
//     res.json(Mock.mock(json));
//   });
//
// }
module.exports = {//导出给谁用呢？
  mocks,
  mockXHR,
  // f//是函数名而不是一个变量，里面装着函数的地址。函数名 vs 变量名装着函数地址
}




